<?php
namespace ESTool;
class Config {
    // ************************************************************
    // ************************************************************
    // ***************** 配置选项  ***********************************
    // ************************************************************
    // ************************************************************
    static public function getKeys($data) {
        $return = array();
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                $return = array_merge((array)$return, self::getKeys($val));
            }
            $return[$key] = $key;
        }
        return $return;
    }
    /**
     * 获取显示字段语言包
     * @param array $replace_langs 需要替换的语言项
     * @return array
     */
    static public function getEsLangsToShowTable($replace_langs, $index='', $returnData=true) {
        $eslang = self::eslang();
        if (!empty($index) && isset($eslang[$index])) {
            $eslang = $eslang[$index];
        } else {
            $eslang = call_user_func_array('array_merge', $eslang);
        }
        $replace_langs['pv'] = 'pv';
        $replace_langs = self::getKeys($replace_langs);
        $eslang = array_intersect_key((array)$eslang, $replace_langs);
        if ($returnData) {
            foreach ($eslang as $key => $data) {
                $eslang[$key]['data'] = Elasticsearchlangdata::getInstance()->get_data($key, $index);
            }
        }
        return $eslang;
    }
    /**
     * 字段映射分析，兼容，不同数据源中，相同类型数据的不同展示形式
     * 例如：城市简拼 city 与  城市代码 bicity,存储数据不同，但意义相同
     * @param string $index 索引
     * @param string $field 字段
     * @param string|array $value 数据值
     * @param string $type 处理方式，encode解析， decode反解
     * @return array($field, $value);  解析后的 字段和对应数值
     */
    static public function FliterFieldMap($index, $field, $value="", $type="decode") {
        // 参数验证，初始化
        $type = strtolower($type);
        $typeList = array("decode", "encode");
        in_array($type, $typeList) || $type = "encode";
        $eslang = model('lang')->_getlang();
        $indexData = array_flip($eslang['index']['data']);
        $map = $eslang['index']['map'];
        // 转换数据
        if (isset($map[$indexData[$index]][$field])) {
            $map = $map[$indexData[$index]][$field];
            $callback = $map[$type."Func"];
            $params = $map[$type."Args"];
            $field = $map[$type."Field"];
            if (!empty($callback)) {
                if (is_array($value)) {
                    foreach ($value as & $v) {
                        $v = call_user_func_array($callback, array_merge((array)$params, array($v)));
                    }
                } else {
                    $value = call_user_func_array($callback, array_merge((array)$params, array($value)));
                }
            }
        }
        return array($field, $value);
        
    }
    /**
     * 获取统计存储数据源对应的汉字名称
     * @return array("agent_day"=>"经纪人统计数据","esf_bi_access_res"=>"访问日志")
     */
    static public function eslangIndexKeyVal() {
        $eslang = model('lang')->_getlang();
        return array_combine($eslang['index']['data'], $eslang['index']['name']);
    }
    /**
     * 获取统计存储数据源对应的存储容器
     * @return array("agent_day"=>"mysql","esf_bi_access_res"=>"es")
     */
    static public function eslangIndexSourceType() {
        $eslang = model('lang')->_getlang();
        return array_combine($eslang['index']['data'], $eslang['index']['type']);
    }
    /**
     * 语言包
     * @return array("index"=>array("field_key"=>array("field"=>"","name"=>"")))
     */
    static public function eslang() {
        $eslang_list = model('lang')->queryByParams('*', ' where `status`=1', ' order by morder,name asc ');
        $eslang = model('lang')->_getlang();
        foreach ($eslang_list as $item) {
            $index_name = $eslang['index']['data'][$item['index']];
            $return[$index_name][$item['field']] = array(
                'name' => $item['name'],
                'field' => $item['field'],
            	'des' => $item['des'],
            );
        }
        return $return;
    }
    /**
     * 通过语言包分组标识，查询使用的统计列
     * @param string $page 语言包分组标识
     * @return array("index"=>array("field_key"=>array("field"=>"","name"=>"")))
     */
    static public function eslangByPage($page="default") {
        $cf = model('langgroup')->getPageParam($page);
        $data = array();
        foreach ($cf as $item) {
            foreach ($item['cl'] as $id => $cl) {
                $data[$cl['index_name']][$cl['field']] = array(
                    'field' => $cl['field'],
                    'name' => $cl['field_name'],
                    'id' => $id,
                    'index' => $cl['index_name'],
                );
            }
        }
        return $data;
    }
    
    /**
     * 获取语言包分组 列表
     * @param string $page 语言包分组标识
     * @return array("index"=>array("field_key"=>array("field"=>"","name"=>"")))
     */
    static public function eslangGroupList($page=1, $pagesize=20) {
        $where['status'] = 1;
        $list = model("langgroup")->_getList($where, $page . "," . $pagesize);
        foreach ($list as $k => $item) {
            $eslang = Config::eslangByPage($item['page']);
            $list[$k]['index'] = array_keys($eslang);
        }
        foreach ($list  as  $item) {
            $item['bi_eslang_id'] = json_decode($item['bi_eslang_id'], true);
            if(!isset($return[$item['page']])) {
                $return[$item['page']] = $item;
            } else {
                is_array($item['bi_eslang_id']) && 
                $return[$item['page']]['bi_eslang_id'] = array_merge((array)$return[$item['page']]['bi_eslang_id'], $item['bi_eslang_id']);
                is_array($item['index']) &&
                $return[$item['page']]['index'] = array_merge((array)$return[$item['page']]['index'], $item['index']);
            }
            $return[$item['page']]['index'] = array_unique($return[$item['page']]['index']);
            $return[$item['page']]['count'][] = $item['type'];
        }
        foreach ($return as $k => $item) {
            if (count($item['count']) < 2) {
                unset($return[$k]);
            }
        }
        return $return;
    }
    /**
     * 筛选条件，元数据
     * @param string $page 语言包分组标识
     */
    static public function optionSource($page="default") {
        return model('langgroup')->getPageParam($page);
    }
    /**
     * 通过语言包分组标识，查询页面展示条件
     * @param string $page 语言包分组标识
     * @param string $type 返回数据类型
     * @return array
     */
    static public function option($page="default", $type="") {
        $fieldList_es = array(
            'rowkey' => array(),
            'cf' => array(),
            'column' => array(),
        );
        $cf = Config::optionSource($page);
        
        foreach (self::getStatColum() as $item) {
            $stat_colum[$item['key']] = $item['name'];
        }
        
        
        foreach ($cf as $item) {
            $data = array();
            foreach ($item['cl'] as $id => $cl) {
                
                $data[$cl['field']]['lang'] = $cl['field_name'];
                $data[$cl['field']]['id'] = $id;
                $data[$cl['field']]['show_type'] = '';
                
                // 为【查询指标】添加扩展属性
                if ($item['type'] == 'column' || $type != "group") {
                    if ($cl['field'] != 'pv') {
                        $data[$cl['field']]['show_type'] = 'group';
                        $data[$cl['field']]['data'] = array(
                            'type' => array(
                                'lang' => '计　　算',
                                'show_type' => 'select',
                                'data' => $stat_colum
                            ),
                        );
                    }
                    
                    continue;
                }
                
                // 为【行为度】【列为度】添加扩展属性
                if (strstr($cl['field'], "time") !== false) {
                    $data[$cl['field']]['show_type'] = 'group';
                    $data[$cl['field']]['data'] =  array(
                        'timeFormat'=>array(
                            'lang' => '时间聚合维度',
                            'show_type' => 'select',
                            'data' => array(
                                '10m' => '10分钟',
                                '30m' => '30分钟',
                                '1h' => '一小时',
                                '3h' => '三小时',
                                '6h' => '六小时',
                                '12h' => '十二小时',
                                '1d' => '一天',
                            )
                        )
                    );
                    continue;
                }
                if (strstr($cl['field'], "geo") !== false) {
                    $data[$cl['field']]['show_type'] = 'group';
                    $data[$cl['field']]['data'] = array(
                        'type' => array(
                            'lang' => '聚合类型',
                            'show_type' => 'select',
                            'data' => array(
                                'grid' => '坐标分组聚合-geohash单元聚合',
                                'distance' => '按距离聚合',
                            )
                        ),
                        'precision' => array(
                            'lang' => '聚合精度',
                            'title' => '坐标分组聚合使用',
                            'show_type' => 'select',
                            'data' => array(
                                '5' => '5',
                                '6' => '6',
                                '7' => '7',
                                '8' => '8',
                                '9' => '9',
                                '10' => '10',
                                '11' => '11',
                                '12' => '12',
                            )
                        ),
                        'origin' => array(
                            'lang' => '中心坐标',
                            'title' => '按距离聚合使用',
                            'show_type' => 'text',
                        ),
                        'ranges' => array(
                            'lang' => '距离取值',
                            'title' => '按距离聚合使用(使用英文逗号分隔)',
                            'show_type' => 'text',
                        ),
                    );
                    continue;
                }
                
                $data[$cl['field']]['show_type'] = 'group';
                $data[$cl['field']]['data'] = array(
                    'size' => array(
                        'lang' => '获取条数',
                        'show_type' => 'text',
                    ),
                    'order' => array(
                        'lang' => '排　　序',
                        'show_type' => 'select',
                        'data' => array(
                            'asc' => '正序',
                            'desc' => '倒序',
                        )
                    ),
                );
                
            }
            $fieldList_es[$item['type']] = array(
                'group_name' => $item['name'],
                'lang' => $item['type_name'],
                'show_type' => 'checkbox',
                'data' => $data,
            );
        }
        return $fieldList_es;
    }
    
    /**
     * 获取百度地图等级
     * @param unknown_type $grade
     * @param unknown_type $type
     * @return number
     */
    public function getMapScale($grade, $type='baidu') {
        $grade > 19 && $grade = 19;
        $grade < 9 && $grade = 9;
        $BMap = array(
            9 => 25 * 1000,
            10 => 20 * 1000,
            11 => 10 * 1000,
            12 => 5 * 1000,
            13 => 2 * 1000,
            14 => 1 * 1000,
            15 => 500,
            16 => 200,
            17 => 100,
            18 => 50,
            19 => 20,
        );
        $EsMap = array(
            '1' =>  array(5004*1000, 5004*1000),
            '2' =>  array(1251*1000, 625*1000),
            '3' =>  array(156*1000, 156*1000),
            '4' =>  array(39*1000, 19.5*1000),
            '5' =>  array(4.9*1000, 4.9*1000),
            '6' =>  array(1.2*1000, 0.61*1000),
            '7' =>  array(152.8, 152.8),
            '8' =>  array(38.2, 19.1),
            '9' =>  array(4.78, 4.78),
            '10' => array(1.19, 0.60),
        );
        foreach ($EsMap as $item) {
            if($item[1] < ceil($BMap[$grade])) {
                $EsGrade = $item[1];
                break;
            }
        }
         
        return $EsGrade;
    }
    static function getStatColum($field, $type="cardinality") {
	    $type_list = array(
            'avg' => array(
				'key' => 'avg',
                'name' => '平均值',
                'field' => '替换字段'
            ),
            'sum' => array(
				'key' => 'sum',
                'name' => '求和',
                'field' => '替换字段'
            ),
            'min' => array(
				'key' => 'min',
                'name' => '最小',
                'field' => '替换字段'
            ),
            'max' => array(
				'key' => 'max',
                'name' => '最大',
                'field' => '替换字段'
            ),
            'extended_stats' => array(
				'key' => 'extended_stats',
                'name' => '标准偏差',
                'field' => '替换字段'
            ),
            'cardinality' => array(
				'key' => 'cardinality',
                'name' => '去重统计',
                'field' => '替换字段'
            ),
	        'percentiles' => array(
				'key' => 'percentiles',
	            'name' => '百分位数',
	            'field' => '替换字段',
	            'percents' => array(
	                0 => 1, 1 => 5, 2 => 25, 3 => 50, 4 => 75, 5 => 95, 6 => 99
	            ),
	            'keyed' => false
	        ),
            'median' => array(
				'key' => 'median',
                'name' => '中位数',
                'field' => '替换字段', 
                'percents' => array(
                    0 => 1, 1 => 5, 2 => 25, 3 => 50, 4 => 75, 5 => 95, 6 => 99
                ),
                'keyed' => false
            ),
        );
	    
	    return $type_list;
	}
	
	/**
	 * 通过groupid获取 需要的id对应的语言包
	 */
	static public function getlangbyid($arr_ids) {
		if(!is_array($arr_ids)){
			return false;
		}
		$str_ids = implode(',',$arr_ids);
		$eslang_list = model('lang')->queryByParams('*', ' where `status`=1', ' order by morder,name asc ');
        $eslang = model('lang')->_getlang();
		foreach ($eslang_list as $item) {
			$index_name = $eslang['index']['data'][$item['index']];
			$return[$index_name][$item['field']] = array(
					'name' => $item['name'],
					'field' => $item['field'],
					'des' => $item['des'],
			);
		}
		return $return;
	}
	
    
}